package cn.fanqinghong.ymcc.service.impl;

import cn.fanqinghong.ymcc.domain.Blacklist;
import cn.fanqinghong.ymcc.domain.MessageSms;
import cn.fanqinghong.ymcc.domain.User;
import cn.fanqinghong.ymcc.feignClient.UserFeignClient;
import cn.fanqinghong.ymcc.mapper.BlacklistMapper;
import cn.fanqinghong.ymcc.result.JSONResult;
import cn.fanqinghong.ymcc.service.IBlacklistService;
import cn.fanqinghong.ymcc.service.IMessageSmsService;
import cn.fanqinghong.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author superman.fan
 * @since 2022-07-18
 */
@Service
public class BlacklistServiceImpl extends ServiceImpl<BlacklistMapper, Blacklist> implements IBlacklistService {

    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private IMessageSmsService messageSmsService;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 增加黑名单
     * @param blacklist
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void saveBlackList(Blacklist blacklist) {
        Blacklist byPhone = selectByPhone(blacklist.getPhone());
        AssertUtil.isNull(byPhone,"该用户已被拉黑");
        //通过传入的id查询sms数据库
        MessageSms messageSms = messageSmsService.selectById(blacklist.getId());


        //判断手机号有没有绑定user_id
        if (messageSms.getUserId()!=null){
            //通过userId查询user的数据，获取到用户的手机号
        Object data = userFeignClient.get(messageSms.getUserId()).getData();
        User user = JSONObject.parseObject(JSON.toJSON(data).toString(), User.class);
        blacklist.setPhone(user.getPhone());
        blacklist.setUserId(user.getId());

        //设置user表中的黑名单状态码为0
        user.setBlackStatic(0);
        userFeignClient.saveOrUpdate(user);
        }
        //如果这个手机号没有被注册
        //保存黑名单
        insert(blacklist);
        saveBlacklistRedis();

    }

    /**
     * 通过手机号查询
     * @param phone
     * @return
     */
    @Override
    public Blacklist selectByPhone(String phone) {
        Wrapper<Blacklist> tWrapper = new EntityWrapper<>();
        tWrapper.eq("phone",phone);
        return selectOne(tWrapper);
    }

    /**
     * 移除黑名单
     * @param id
     */
    @Override
    public void deleteByIdUser(Long id) {
        Blacklist blacklist = selectById(id);
        if (blacklist.getUserId()!=null){
            //通过userId查询user的数据，获取到用户的手机号
            Object data = userFeignClient.get(blacklist.getUserId()).getData();
            User user = JSONObject.parseObject(JSON.toJSON(data).toString(), User.class);
            //设置user表中的黑名单状态码为1
            user.setBlackStatic(1);
            userFeignClient.saveOrUpdate(user);
        }
        deleteById(id);
        saveBlacklistRedis();

    }

    /**
     * 存储数据到redis中
     */
    private void saveBlacklistRedis() {
        //删除redis表
        redisTemplate.delete("blacklists");
        //查询黑名单
        List<Blacklist> blacklists = selectList(null);
        //把黑名单存入redis中
        for(Blacklist data : blacklists){
            redisTemplate.opsForList().rightPush("blacklists",data);
        }
    }

    @Override
    public Page<Blacklist> selectPageRedis(Page<Blacklist> page) {
        //获取到分页总条数
        int count = selectCount(null);
        //当前页
        int current = page.getCurrent();
        //每页条数
        long pages = page.getSize();
        //当前页从第几条数据开始
        long start = (current - 1) * pages;
        long end = 0;
        List<Object> data = new ArrayList<>();
        //如果(分页总条数-当前页*每页条数) 的余数 >= 0
        if ((count-current*pages) >= 0){
            end = pages * current - 1;
             data = redisTemplate.opsForList().range("blacklists",start , end);
        }
        //如果(分页总条数-当前页*每页条数)的余数 < 0
        if ((count-current*pages) < 0){
            data = redisTemplate.opsForList().range("blacklists",start , count);
        }

        List<Blacklist> blacklists = JSONArray.parseArray(JSON.toJSON(data).toString(), Blacklist.class);

        Page<Blacklist> blacklistPage = new Page<>();
        blacklistPage.setTotal(count);
        blacklistPage.setRecords(blacklists);
        return blacklistPage;
    }
}
